<?php defined('BASEPATH') || exit('No direct script access allowed');

class Buildingstag_model extends BF_Model
{
    protected $table_name	= 'building_tag';
	protected $key			= 'id';
	protected $date_format	= 'datetime';

    protected $tags_table   = 'tags';

	protected $log_user 	= false;
    protected $set_created	= false;
	protected $set_modified = false;
	protected $soft_deletes	= false;

	// Customize the operations of the model without recreating the insert,
    // update, etc. methods by adding the method names to act as callbacks here.
	protected $before_insert 	= array();
	protected $after_insert 	= array();
	protected $before_update 	= array();
	protected $after_update 	= array();
	protected $before_find 	    = array();
	protected $after_find 		= array();
	protected $before_delete 	= array();
	protected $after_delete 	= array();

	// For performance reasons, you may require your model to NOT return the id
	// of the last inserted row as it is a bit of a slow method. This is
    // primarily helpful when running big loops over data.
	protected $return_insert_id = true;

	// The default type for returned row data.
	protected $return_type = 'object';

	// Items that are always removed from data prior to inserts or updates.
	protected $protected_attributes = array();

	// You may need to move certain rules (like required) into the
	// $insert_validation_rules array and out of the standard validation array.
	// That way it is only required during inserts, not updates which may only
	// be updating a portion of the data.
	protected $validation_rules 		= array(

	);
	protected $insert_validation_rules  = array();
	protected $skip_validation 			= false;

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function prep_data($post_data) {
        $data = parent::prep_data($post_data);

        return $data;
    }

    /**
     * 给楼盘添加分类
     *
     * @param int $buildingId 楼盘ID
     * @param array $categories 标签ID数组
     * @return mixed 成功返回添加的条数，否则返回false
     */
    public function addCategories($buildingId, $categories) {
        $return = false;
        if (is_array($categories)) {
            foreach ($categories as $key => $val) {
                $data[] = array('tag_id'=>$val, 'building_id'=>$buildingId, 'type'=>3);
            }
            $return = $this->db->insert_batch($this->table_name, $data);
        }
        return $return;
    }

    
    /**
     * 更新楼盘分类
     *
     * @param int $buildingId 楼盘ID
     * @param array $categories 标签ID数组
     * @return mixed 成功返回添加的条数，否则返回false
     */
    public function updateCategories($buildingId, $categories) {

        // 删除已有的数据
        parent::delete_where(array('building_id'=>$buildingId, 'type'=>3));
        // 新增        
        return $this->addCategories($buildingId, $categories);
    }

    /**
     * 添加标签
     * @param int $buildingId 楼盘ID
     * @param int $type       标签类型
     * @param array $tags       标签数组
     * @return mixed 成功返回添加的条数，否则返回false
     */
    public function addTags($buildingId, $type, $tags) {
        $return = false;
        if (!empty($tags) && is_array($tags) && $buildingId) {
            // 删除已有的数据
            parent::delete_where(array('building_id'=>$buildingId, 'type'=>$type));
            // 查询标题基础表，得到 tag_id
            $this->load->model('tags/tags_model');
            foreach ($tags as $tag) {
                $tagId = null;
                if (is_numeric($tag)) {
                    // 标签ID，这里是从编辑页面提交过来存在的标签
                    $tagId = $tag;
                } else {
                    $tagData = $this->tags_model->find_by('tag_name', $tag);
                    if (empty($tagData))  {
                        // 新增标签基础表
                        $tagId = $this->tags_model->insert(array('tag_name'=>$tag));
                    } else {
                        $tagId = $tagData->tag_id;
                    }
                }
                $tagIdArr[] = $tagId;
            }
            // 新增
            foreach ($tagIdArr as $val) {
                $data[] = array('tag_id'=>$val, 'building_id'=>$buildingId, 'type'=>$type);
            }
            $return = $this->db->insert_batch($this->table_name, $data);
        }
        return $return;
    }

    /**
     * 获取楼盘标签，type为0获取全部标签
     * @param  int $buildingId 楼盘ID
     * @param  int $type       标签类型
     * @return mixed 成功返回数据，否则返回false
     */
    public function tags($buildingId, $type = 0) {
        if (empty($buildingId)) return false;

        $where['building_id'] = $buildingId;
        if ($type > 0) $where['type'] = $type;
        $this->db->select(array("{$this->tags_table}.tag_name", "{$this->tags_table}.tag_id", "{$this->table_name}.type"))
                 ->where($where)
                 ->from($this->table_name)
                 ->order_by("{$this->table_name}.type")
                 ->join($this->tags_table, "{$this->tags_table}.tag_id = {$this->table_name}.tag_id", 'left');

        $query = $this->db->get();
        if ($query->num_rows()) {
            $result = $query->result();
            if ($type == 0) {
                // 取全部标签，整理标签归类
                foreach ($result as $val) {
                    $typeCode = building_tag_type_code()[$val->type];
                    $data[$typeCode][] = $val;
                }
                return $data;
            }
            return $result;
        }

        return false;
    }
}